package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareInfoService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneItemVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        wrapper.eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode()).or().eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergeUnreceivePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        Long finalPurchaseId = purchaseId;
        //TODO 采购单总金额和仓库要填写完成。
        PurchaseEntity byId = this.getById(finalPurchaseId);
        //只有状态为创建和已分配的采购单才合并
        if (byId.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || byId.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {

            List<PurchaseDetailEntity> collect = mergeVo.getItems().stream().map((i) -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setPurchaseId(finalPurchaseId);
                detailEntity.setId(i);
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
               //从purchaseDetail 中找sku_price by purchaseDetailId=i
               detailEntity.setSkuPrice(purchaseDetailService.getById(i).getSkuPrice());
                return detailEntity;
            }).collect(Collectors.toList());


            purchaseDetailService.updateBatchById(collect);
            //更新采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(finalPurchaseId);
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setPriority(1);
            //仓库ID
            purchaseEntity.setWareId(collect.get(0).getWareId());
            BigDecimal amount= BigDecimal.valueOf(0);

            for (int i = 0; i < collect.size(); i++) {
                amount=collect.get(i).getSkuPrice().add(amount);
            }
            purchaseEntity.setAmount(amount);
            this.updateById(purchaseEntity);
        }
    }

    @Transactional
    @Override
    public void receivePurchase(List<Long> ids) {
        //1.采购单是已分配的
        if (ids != null) {


            List<PurchaseEntity> collect = ids.stream().map((id) -> {
                PurchaseEntity purchaseEntity = this.getById(id);
                return purchaseEntity;
            }).filter(item -> {
                if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                        || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                    return true;
                }
                return false;
            }).map((item) -> {
                item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
                item.setUpdateTime(new Date());
                return item;
            }).collect(Collectors.toList());
            //2.修改采购需求中状态为正在采购
            this.updateBatchById(collect);
            //3.修改采购单状态为已领取
            collect.forEach((item) -> {
                List<PurchaseDetailEntity> entities = purchaseDetailService.listDetailByPurchaseId(item.getId());
                List<PurchaseDetailEntity> detailEntities = entities.stream().map((detail) -> {
                    PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                    detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                    detailEntity.setId(detail.getId());
                    return detailEntity;
                }).collect(Collectors.toList());
                purchaseDetailService.updateBatchById(detailEntities);
            });
        }

    }

    @Override
    public void donePurchase(PurchaseDoneVo doneVo) {


            //3.修改采购需求项  商品id为采购完成或采购失败
            //TODO:PurchaseDetail 表可以完善，如原因，计划采购多少，实际采购多少
            List<PurchaseDoneItemVo> items = doneVo.getItems();
            boolean flag=true;
            List<PurchaseDetailEntity>update=new ArrayList<>();
            for(PurchaseDoneItemVo item :items){
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(item.getItemId());
                //TODO BeanUtils.cp? item detailEntity no
                if(item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                    flag=false;
                    detailEntity.setStatus(item.getStatus());
                }else{
//                    flag=true; 这里不要写，否则会把采购失败覆盖，出错了也得不到结果的。
                    detailEntity.setStatus(item.getStatus());
                    //4.修改库存中采购需要中商品id的数量，即将成功采购进行入库
                    //需要3个参数：sku_id, ware_id（几号库）， and stock(数量)
                    PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item.getItemId());
                    wareSkuService.addStock(purchaseDetail.getWareId() ,purchaseDetail.getSkuId(),purchaseDetail.getSkuNum());
                }
                detailEntity.setReason(item.getReason());
                update.add(detailEntity);
            }
            purchaseDetailService.updateBatchById(update);
        Long purchaseId = doneVo.getId();
        if (purchaseId!=null){
            //1.判断采购单为   已领取状态
            PurchaseEntity byId = this.getById(purchaseId);
            if (byId.getStatus()==WareConstant.PurchaseStatusEnum.RECEIVED.getCode()){
                PurchaseEntity purchaseEntity = new PurchaseEntity();
                purchaseEntity.setId(purchaseId);
                purchaseEntity.setUpdateTime(new Date());
                //2.修改采购单为   已完成或有异常(有一个为不成功，即报有异常)
                purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISHED.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
                this.updateById(purchaseEntity);
            }
        }
    }

}